﻿using FileStorageCenter;
using FileStorageCenter.Services.Models;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System.Security.Claims;

namespace Microsoft.EntityFrameworkCore;

public static class DbContextExtensions
{
    public static User CurrentUser(this DbContext ctx)
    {
        var account = App.HttpContext!.User.Claims.FirstOrDefault(n => n.Type is "name" or ClaimTypes.Name)!.Value;

        return ctx.Set<User>().First(n => n.Account == account);
    }

    public static EntityEntry<TEntity>? TryAttach<TEntity>(this DbContext context, TEntity entity)
        where TEntity : class
    {
        var keys = context.Model.FindEntityType(typeof(TEntity))?.FindPrimaryKey()?.Properties.Select(e => e.Name)!;

        var entry = context.Entry(entity);

        foreach (var entityEntry in context.ChangeTracker.Entries<TEntity>())
        {
            var mismatch = false;
            foreach (var key in keys)
            {
                if (!Equals(entityEntry.Property(key).CurrentValue, entry.Property(key).CurrentValue))
                {
                    mismatch = true;
                    break;
                }
            }
            if (!mismatch)
            {
                return entityEntry;
            }
        }

        return null;
    }
}